<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/16
 * Time: 14:32
 */

namespace App\Spider;

use EasySwoole\EasySwoole\Logger;
use EasySwoole\HttpClient\Bean\Response;
use EasySwoole\HttpClient\HttpClient;
use EasySwoole\RedisPool\Redis;


class HttpClientLogic
{
    static function getHtmlContent($url,$i = 1):?Response
    {
        if( $i >= 100 ){
            Logger::getInstance()->console('302跳转次数太多，已终止',Logger::LOG_LEVEL_WARNING);
            return false;
        }
        $httpClient = new HttpClient($url);
        $cookie = self::getDomainCookie(self::getUrlDomain($url));
        if( $cookie ){
            $httpClient->getClient()->setCookies($cookie);
        }
        $response = $httpClient->get([
            'referer' => $url
        ]);

        if ($response->getStatusCode() == '302') {
            return self::getHtmlContent(self::getTrueUrl($url, $response->getHeaders()['location']), $i + 1);
        }
        if ($response->getStatusCode() == '-3') {
            //return self::getHtmlContent(self::getTrueUrl($url, $response->getHeaders()['location']), $i + 1);
            return self::getHtmlContent($url,$i + 1);
        }
        self::setDomainCookie(self::getUrlDomain($url), $response->getCookies());
        return $response;
    }

    static function getUrlDomain($url)
    {
        $urlInfo = parse_url($url);
        return $urlInfo['host'];
    }

    static function getDomainCookie($domain)
    {
        return Redis::invoker('redis',function (\Swoole\Coroutine\Redis $redis)use($domain){
            $cookieListKey = 'cookieList';
            $cookie = $redis->hGet($cookieListKey,$domain);
            return $cookie;
        });
    }

    static function setDomainCookie($domain,$cookie)
    {
        return Redis::invoker('redis',function (\Swoole\Coroutine\Redis $redis)use($domain,$cookie){
            $cookieListKey = 'cookieList';
            $result = $redis->hSet($cookieListKey,$domain,$cookie);
            return $result;
        });
    }

    static function getTrueUrl($preUrl,$link)
    {
        $urlInfo = parse_url($preUrl);
        //分析path
        if (isset($urlInfo['path'])){
            $pathArr = explode('/',$urlInfo['path']);
            if (!empty($pathArr[count($pathArr)-1])){
                array_pop($pathArr);
                $urlInfo['path'] = implode('/',$pathArr);
            }
        }else{
            $urlInfo['path']='/';
        }
        if (substr($link, 0, 1) == '/') {
            $url = $urlInfo['scheme'] . '://' . $urlInfo['host'] . $link;
        } elseif (substr($link, 0, 2) == './') {
            $url = $urlInfo['scheme'] . '://' . $urlInfo['host'].$urlInfo['path'].'/' . $link;
        } else {
            $url = $urlInfo['scheme'] . '://' . $urlInfo['host'].$urlInfo['path'].'/' . $link;
        }
        return $url;
    }
}